<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j component-pic-upload">
    <el-upload
      :disabled="disabled"
      action=""
      :headers="{ Authorization: token }"
      :show-file-list="false"
      :http-request="handleFileChange"
      :before-upload="beforeAvatarUpload"
      style="width:100%;height:100%;"
    >
      <img
        v-if="resourcesVal"
        :src="checkFileUrl(resourcesVal)"
        class="pic avatar"
        alt
      >
      <el-icon
        v-else
        class="add-icon"
        size="28"
        color="#909399"
      >
        <Plus />
      </el-icon>
    </el-upload>
  </div>
</template>

<script setup>
import Cookie from 'vue-cookies'
import imageCompression from 'browser-image-compression'
import { ElMessage } from 'element-plus'
import { checkFileUrl } from '@/utils/index.js'
const props = defineProps({
  modelValue: {
    default: '',
    type: String
  },
  disabled: {
    default: false,
    type: Boolean
  },
  fullUrl: {
    default: false,
    type: Boolean
  }
})
const emit = defineEmits(['update:modelValue'])

const token = computed(() => {
  return Cookie.get('bbcToken')
})

const resourcesVal = ref('')
let inited = false
watch(() => props.modelValue, (newVal, oldVal) => {
  if (!oldVal && newVal && !inited) {
    resourcesVal.value = checkFileUrl(newVal)
    inited = true
  }
}, { immediate: true })

// 限制图片上传大小
const beforeAvatarUpload = async (file) => {
  // 判断图片类型来筛选图片格式上传
  const _type = file.type
  if (_type.indexOf('png') === -1 && _type.indexOf('jpg') === -1 && _type.indexOf('jpeg') === -1) {
    ElMessage.error($t('imageNoformatUpload'))
    return Promise().reject()
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    try {
      const resultBlob = await imageCompression(file, {
        maxSizeMB: 10 // 压缩大小
      })
      return new File([resultBlob], file.name, {
        type: file.type
      })
    } catch (error) {
      return Promise().reject()
    }
  }
}
const handleFileChange = (e) => {
  const file = e.file
  http({
    url: '/p/file/getPreSignUrl',
    method: 'get',
    params: {
      fileName: file.name,
      isImFile: false
    }
  }).then(async ({ data }) => {
    await uploadFile(data.preSignUrl, file).then(() => {
      http({
        url: '/p/file/uploadSuccess',
        method: 'put',
        data: [
          {
            fileId: data.fileId,
            attachFileGroupId: 0,
            fileSize: file.size
          }
        ]
      }).then(() => {
        inited = true
        resourcesVal.value = checkFileUrl(data.filePath)
        if (props.fullUrl) {
          emit('update:modelValue', resourcesVal.value)
        } else {
          emit('update:modelValue', data.filePath)
        }
      })
    })
  })
}
</script>

<style lang="scss" scoped>
.component-pic-upload {
  width: 100%;
  height: 100%;
  &:deep(.el-upload) {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    .pic {
      max-width: 100%;
      max-height: 100%;
    }
  }
  .add-icon{
    // eslint-disable-next-line vue-scoped-css/no-unused-selector
    svg{
      width: 100%;
      height: 100%;
    }
  }
}
</style>
